package com.kin207.netty;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.handle.IMessageHandle;
import com.kin207.netty.handle.MessageHandles;
import com.kin207.netty.handle.adapter.HeadMessageHandleAdapter;
import com.kin207.netty.msg.parse.SplitMessageParse;
import com.kin207.netty.session.SessionManager;
import com.kin207.netty.udp.UdpChannelInboundHandler;
import com.kin207.netty.udp.UdpChannelInitializer;
import com.kin207.netty.udp.UdpServer;

import io.netty.channel.ChannelHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class UdpServerRun {
	final static Logger logger = LoggerFactory.getLogger(UdpServerRun.class );
	
	public static void main(String[] args) {
		//UdpSessionManager sessionManager = new UdpSessionManager();
		//SessionManager sessionManager = new SessionManager();
		SessionManager sessionManager = SessionManager.newInstance();
		
		final int port = args.length>0?Integer.parseInt(args[0]):8378;
		Map<String,IMessageHandle> handles = MessageHandles.newInstance().getHandles();
		final UdpServer server = new UdpServer(port);
		
		HeadMessageHandleAdapter messageHandleAdapter = new HeadMessageHandleAdapter();
		messageHandleAdapter.setHandles(handles);
		
		SplitMessageParse messageParse = new SplitMessageParse();
		
		UdpChannelInboundHandler channelInboundHandler = new UdpChannelInboundHandler();
		channelInboundHandler.setServer(server);
		
		Map<String, ChannelHandler> channelHandlers = new LinkedHashMap();
		channelHandlers.put("idleStateHandler", new IdleStateHandler(2, 2, 2, TimeUnit.SECONDS));
		channelHandlers.put("handler", channelInboundHandler);
		
		UdpChannelInitializer channelInitializer = new UdpChannelInitializer();
		channelInitializer.setInitHandles(channelHandlers);
		
		server.setSessionManager(sessionManager);
		server.setChannelInitializer(channelInitializer);
		server.setMessageHandleAdapter(messageHandleAdapter);
		server.setMessageParse(messageParse);
		
		Executors.newSingleThreadExecutor().submit(new Runnable() {
			public void run() {
				logger.info("udp server run, prot:{}", port);
				try {
					server.run();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		if(args.length<1 || "in".equals(args[1])){
			Scanner scann = new Scanner(System.in);
			while(true){
				System.out.print("请输入:");
				String msg = scann.nextLine();
				server.getSessionManager().sendSystemMessage(msg,System.currentTimeMillis());
			}
		}
		
	}
}
